package com.everest.tribalapp;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.everest.tribalapp.Dering_Pengelola_1.Check;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.*;

public class Desa_Form1 extends Activity implements OnItemSelectedListener
{

	private Button next;
	//private EditText desa_f1_ans_6;
	private EditText desa_f1_ans_5;
	private String[] selectid;
	private String[] selectname;
	private ArrayList<String> stringArrayList1;
	private ArrayList<String> stringArrayList2;
	private Spinner s;
	private String[] select_district;
	private String[] select_sub;
	private ArrayList<String> stringArrayList3;
	private String[] select_desa;
	
	private String[] selectidkotakabupaten;
	private String[] selectnamekotakabupaten;
	private String[] selectidkecamatan;
	private String[] selectnamekecamatan;
	private String[] selectiddesa;
	private String[] selectnamedesa;
	
	private Spinner s1;
	private Spinner s2;
	private Spinner s3;
	private ArrayList<String> stringArrayList11;
	private ArrayList<String> stringArrayList12;
	
	private ArrayList<String> stringArrayList21;
	private ArrayList<String> stringArrayList22;
	
	private ArrayList<String> stringArrayList31;
	private ArrayList<String> stringArrayList32;
	
	private ArrayList<String> stringArrayList41;
	private ArrayList<String> stringArrayList42;
	

	@Override
	public void onBackPressed() 
	{
		// TODO Auto-generated method stub
		super.onBackPressed();
		Intent intent=new Intent(getApplicationContext(), Add1.class);
		startActivity(intent);
		Desa_Form1.this.finish();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		Desa_Form1.this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.desa_f1);
		
		s=(Spinner)findViewById(R.id.desa_f1_ans_1);
		s1=(Spinner)findViewById(R.id.desa_f1_ans_2);
		s2=(Spinner)findViewById(R.id.desa_f1_ans_3);
		s3=(Spinner)findViewById(R.id.desa_f1_ans_4);
		Boolean a;
		 a=isOnline();
		 if(a)
		 {
		 new Check().execute();
		 }
		 else
		 {
			 
				ArrayAdapter adapter = new ArrayAdapter(Desa_Form1.this,android.R.layout.simple_spinner_item, Global.province);
				s.setAdapter(adapter);
				ArrayAdapter adapter1 = new ArrayAdapter(Desa_Form1.this,android.R.layout.simple_spinner_item, Global.district);
				s1.setAdapter(adapter1);
				ArrayAdapter adapter2 = new ArrayAdapter(Desa_Form1.this,android.R.layout.simple_spinner_item, Global.subdistrict);
				s2.setAdapter(adapter2);
				ArrayAdapter adapter3 = new ArrayAdapter(Desa_Form1.this,android.R.layout.simple_spinner_item, Global.desa);
				s3.setAdapter(adapter3);
				
		 }
		//desa_f1_ans_6=(EditText)findViewById(R.id.desa_f1_ans_6);
		desa_f1_ans_5=(EditText)findViewById(R.id.desa_f1_ans_5);
		next=(Button)findViewById(R.id.desa_f1_next);
		next.setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				Intent intent=new Intent(getApplicationContext(),Desa_Form2.class);
				startActivity(intent);
				Desa_Form1.this.finish();
			}
		});
		
	}

	@Override
	protected void onPause()
	{
		// TODO Auto-generated method stub
		super.onPause();
		SharedPreferences preferences=getSharedPreferences("desa_f1_details",MODE_PRIVATE);
		SharedPreferences.Editor editor=preferences.edit();
		//editor.putString("1_6",desa_f1_ans_6.getText().toString().trim());
		editor.putString("1_5",desa_f1_ans_5.getText().toString().trim());
		editor.putString("1_1",s.getSelectedItem().toString().trim());
		editor.putString("1_2",s1.getSelectedItem().toString().trim());
		editor.putString("1_3",s2.getSelectedItem().toString().trim());
		editor.putString("1_4",s3.getSelectedItem().toString().trim());
		editor.commit();
	}

	@Override
	protected void onResume()
	{
		// TODO Auto-generated method stub
		super.onResume();
		SharedPreferences preferences=getSharedPreferences("desa_f1_details",MODE_PRIVATE);
		desa_f1_ans_5.setText(preferences.getString("1_5",""));
		//desa_f1_ans_6.setText(preferences.getString("1_6",""));
	}
	protected void province()
	{
		   boolean answer;
	        answer=isOnline();
	        System.out.println(answer);
          	stringArrayList11 = new ArrayList<String>();
          	stringArrayList12 = new ArrayList<String>();
	        
	        if(answer)
	        {
	                 
	        JSONObject json = JSONfunctions.getJSONfromURL(Global.desa_propinsi_url);           
		        try{
	        	JSONObject response1=json.getJSONObject("response");
	          	response1.toString();
	        	JSONArray  data = response1.getJSONArray("items");
	        	
	        
	            for(int i=0;i<data.length();i++)
	            {						
	    			
	    			JSONObject e = data.getJSONObject(i);
	    			     
	    			     stringArrayList12.add(e.getString("name"));
	    			     	
	    			     
	            	
	            }	
	            //selectid = stringArrayList11.toArray(new String[stringArrayList11.size()]);
	            selectname = stringArrayList12.toArray(new String[stringArrayList12.size()]);
	            System.out.println(selectname[0]);
	        }catch(JSONException e)        
	        {
	        	System.out.println(e);
	        	 Log.e("log_tag", "Error parsing data "+e.toString());
	        }
	        
	       
	       
	    }
	    else
	    {

	    	Toast.makeText(getApplicationContext(), "No Internet Connection",Toast.LENGTH_LONG).show();
	    } 
		
	}
	protected void detail()
	{
		   boolean answer;
	        answer=isOnline();
	        System.out.println(answer);
          	stringArrayList1 = new ArrayList<String>();
          	stringArrayList2 = new ArrayList<String>();
          	stringArrayList3 = new ArrayList<String>();
	        
	        if(answer)
	        {
	                 
	        JSONObject json = JSONfunctions.getJSONfromURL(Global.detail_url);           
		        try{
	        	JSONObject response1=json.getJSONObject("response");
	          	response1.toString();
	        	JSONArray  data = response1.getJSONArray("items");
	        	
	        
	            for(int i=0;i<data.length();i++)
	            {						
	    			
	    			JSONObject e = data.getJSONObject(i);
	    			     stringArrayList1.add(e.getString("district"));
	    			     stringArrayList2.add(e.getString("sub_district"));
	    			     stringArrayList3.add(e.getString("desa"));
	    			
	            }	
	            select_district = stringArrayList1.toArray(new String[stringArrayList1.size()]);
	            select_sub = stringArrayList2.toArray(new String[stringArrayList2.size()]);
	            select_desa = stringArrayList3.toArray(new String[stringArrayList3.size()]);
	            System.out.println(selectname[0]);
	        }catch(JSONException e)        
	        {
	        	System.out.println(e);
	        	 Log.e("log_tag", "Error parsing data "+e.toString());
	        }
	        
	       
	       
	    }
	    else
	    {

	    	Toast.makeText(getApplicationContext(), "No Internet Connection",Toast.LENGTH_LONG).show();
	    } 
		
	}
	public boolean isOnline() 
	{
	    ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo netInfo = cm.getActiveNetworkInfo();
	    if (netInfo != null && netInfo.isConnectedOrConnecting())
	    {
	        return true;
	    }
	    return false;
	}
	
	
	
	class Check extends AsyncTask{
		//
				
				private String json;
				private JSONObject jsonobject;
				private String code;
				private String msg;
				private String url;
				private Dialog dialog;
				@Override
				protected void onPreExecute() 
				{
					super.onPreExecute();
					dialog=new Dialog(Desa_Form1.this);
					dialog.setTitle("Loading...");
					dialog.setCancelable(false);
					dialog.show();
					
				}

				@Override
				protected Object doInBackground(Object... params) 
				{
					
					try 
					{
						province();
						//detail();
					} 
					catch (Exception e) 
					{
						e.printStackTrace();
					}
					return null;
				}
				@Override
				
				protected void onPostExecute(Object result)
				{
					
					if(selectname.length>0)
					{
					ArrayAdapter adapter = new ArrayAdapter(Desa_Form1.this,android.R.layout.simple_spinner_item, selectname);
					s.setAdapter(adapter);
						
					s.setOnItemSelectedListener(
			                new OnItemSelectedListener() {
			                    public void onItemSelected(
			                            AdapterView<?> parent, View view, int position, long id) {
			                    	
			                    	boolean answer;
			            	        answer=isOnline();
			            	        System.out.println(answer);
			                      	stringArrayList11 = new ArrayList<String>();
			                      	stringArrayList12 = new ArrayList<String>();
			                      	
			                      	String vprovince = parent.getItemAtPosition(position).toString();
			                      	try {
										vprovince=URLEncoder.encode(vprovince,"UTF-8");
										System.out.println(vprovince);
				            	        if(answer)
				            	        {	
				            	        	
					                    	JSONObject json = JSONfunctions.getJSONfromURL(Global.desa_kotakabupaten_url + vprovince);           
					        		        try{
						        	        	JSONObject response1=json.getJSONObject("response");
						        	          	response1.toString();
						        	        	JSONArray  data = response1.getJSONArray("items");
						        	        	
						        	        
						        	            for(int i=0;i<data.length();i++)
						        	            {						
						        	    			
						        	    			JSONObject e = data.getJSONObject(i);
						        	    			     stringArrayList12.add(e.getString("name"));
						        	    			 
						        	            }	
						        	            
						        	            selectnamekotakabupaten = stringArrayList12.toArray(new String[stringArrayList12.size()]);
						        	            if (selectnamekotakabupaten.length>0){
						            	        	ArrayAdapter adapter1 = new ArrayAdapter(Desa_Form1.this,android.R.layout.simple_spinner_item, selectnamekotakabupaten);
						            	        	s1.setAdapter(adapter1);
						            	        		
						            	        			s1.setOnItemSelectedListener(
						    				                new OnItemSelectedListener() {
						    				                    public void onItemSelected(
						    				                            AdapterView<?> parent3, View view3, int position3, long id) {
						    				                    	
						    				                        //showToast("Spinner2: position=" + position + " id=" + id);
						    				                    	Toast.makeText(parent3.getContext(), "You selected: ",
						    				                				Toast.LENGTH_LONG).show();
						    				                    	boolean answer;
						    				            	        answer=isOnline();
						    				            	        System.out.println(answer);
						    				                      	stringArrayList31 = new ArrayList<String>();
						    				                      	stringArrayList32 = new ArrayList<String>();
						    				                      	
						    				                      	String vkotakabupaten = parent3.getItemAtPosition(position3).toString();
						    				                      	try {
						    				                      		vkotakabupaten=URLEncoder.encode(vkotakabupaten,"UTF-8");
						    											System.out.println(vkotakabupaten);
						    					            	        if(answer)
						    					            	        {	
						    					                    		
						    						                    	JSONObject json = JSONfunctions.getJSONfromURL(Global.desa_kecamatan_url + vkotakabupaten);           
						    						        		        try{
						    							        	        	JSONObject response1=json.getJSONObject("response");
						    							        	          	response1.toString();
						    							        	        	JSONArray  data = response1.getJSONArray("items");
						    							        	        	
						    							        	        
						    							        	            for(int i=0;i<data.length();i++)
						    							        	            {						
						    							        	    			
						    							        	    			JSONObject e = data.getJSONObject(i);
						    							        	    			     
						    							        	    			     stringArrayList32.add(e.getString("name"));
						    							        	    			     	
						    							        	    			     
						    							        	            	
						    							        	            }	
						    							        	            
						    							        	            selectnamekecamatan = stringArrayList32.toArray(new String[stringArrayList32.size()]);
						    							        	            if (selectnamekecamatan.length>0){
									    				            	        	ArrayAdapter adapter2 = new ArrayAdapter(Desa_Form1.this,android.R.layout.simple_spinner_item, selectnamekecamatan);
									    				            	        	s2.setAdapter(adapter2);
									    				            	        		
									    				            	        		/*desa*/
									    				            	        	s2.setOnItemSelectedListener(
														    				                new OnItemSelectedListener() {
														    				                    public void onItemSelected(
														    				                            AdapterView<?> parent4, View view4, int position4, long id4) {
														    				                    	
														    				                    	
														    				                    	boolean answer;
														    				            	        answer=isOnline();
														    				            	        System.out.println(answer);
														    				                      	stringArrayList41 = new ArrayList<String>();
														    				                      	stringArrayList42 = new ArrayList<String>();
														    				                      	
														    				                      	String vkecamatan = parent4.getItemAtPosition(position4).toString();
														    				                      	try {
														    				                      		vkecamatan=URLEncoder.encode(vkecamatan,"UTF-8");
														    											System.out.println(vkecamatan);
														    					            	        if(answer)
														    					            	        {	
														    					                    		
														    						                    	JSONObject json = JSONfunctions.getJSONfromURL(Global.desa_url + vkecamatan);           
														    						        		        try{
														    							        	        	JSONObject response1=json.getJSONObject("response");
														    							        	          	response1.toString();
														    							        	        	JSONArray  data = response1.getJSONArray("items");
														    							        	        	
														    							        	        
														    							        	            for(int i=0;i<data.length();i++)
														    							        	            {						
														    							        	    			
														    							        	    			JSONObject e = data.getJSONObject(i);
														    							        	    			     
														    							        	    				stringArrayList41.add(e.getString("id"));
														    							        	    			    stringArrayList42.add(e.getString("desa"));
														    							        	    			     	
														    							        	    			     
														    							        	            	
														    							        	            }	
														    							        	            selectiddesa = stringArrayList41.toArray(new String[stringArrayList41.size()]);
														    							        	            selectnamedesa = stringArrayList42.toArray(new String[stringArrayList42.size()]);
														    							        	            if (selectnamedesa.length>0){
																	    				            	        	ArrayAdapter adapter4 = new ArrayAdapter(Desa_Form1.this,android.R.layout.simple_spinner_item, selectnamedesa);
																	    				            	        	s3.setAdapter(adapter4);
																	    				            	        	
																	    				            	        		
																	    				            	        	
																	    				            	        }
														    							        	        }catch(JSONException e)        
														    							        	        {
														    							        	        	System.out.println(e);
														    							        	        	 Log.e("log_tag", "Error parsing data desa "+e.toString());
														    							        	        } 
														    					        		       
														    					            	        }
														    										} catch (UnsupportedEncodingException e1) {
														    											// TODO Auto-generated catch block
														    											e1.printStackTrace();
														    										}
														    				                      	
														    				            	        
														    				                    	
														    				                    }

														    				                    public void onNothingSelected(AdapterView<?> parent) {
														    				                       // showToast("Spinner2: unselected");
														    				                    }
														    				                });
									    				            	        		/*end desa*/
									    				            	        	
									    				            	        }
						    							        	        }catch(JSONException e)        
						    							        	        {
						    							        	        	System.out.println(e);
						    							        	        	 Log.e("log_tag", "Error parsing data "+e.toString());
						    							        	        } 
						    					        		       
						    					            	        }
						    										} catch (UnsupportedEncodingException e1) {
						    											// TODO Auto-generated catch block
						    											e1.printStackTrace();
						    										}
						    				                      	
						    				            	        
						    				                    	
						    				                    }

						    				                    public void onNothingSelected(AdapterView<?> parent) {
						    				                       // showToast("Spinner2: unselected");
						    				                    }
						    				                });
						            	        	
						            	        }
						        	        }catch(JSONException e)        
						        	        {
						        	        	System.out.println(e);
						        	        	 Log.e("log_tag", "Error parsing data "+e.toString());
						        	        } 
				        		       
				            	        }
									} catch (UnsupportedEncodingException e1) {
										// TODO Auto-generated catch block
										e1.printStackTrace();
									}
			                      	
			            	        
			                    	
			                    }

			                    public void onNothingSelected(AdapterView<?> parent) {
			                       // showToast("Spinner2: unselected");
			                    }
			                });
						
					}
					/*if(select_district.length>0)
					{
						ArrayAdapter adapter1 = new ArrayAdapter(Desa_Form1.this,android.R.layout.simple_spinner_item, select_district);
						s1.setAdapter(adapter1);
					}
					if(select_sub.length>0)
					{
						ArrayAdapter adapter2 = new ArrayAdapter(Desa_Form1.this,android.R.layout.simple_spinner_item, select_sub);
						s2.setAdapter(adapter2);
					}
					if(select_desa.length>0)
					{
						ArrayAdapter adapter3 = new ArrayAdapter(Desa_Form1.this,android.R.layout.simple_spinner_item, select_desa);
						s3.setAdapter(adapter3);
					} */
					
					dialog.dismiss();
					
				}

			}



	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}
}
